package cn.xshi.sys.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import cn.xshi.sys.dao.SysNotifyReceiverDao;
import cn.xshi.sys.service.SysNotifyReceiverService;
import cn.xshi.sys.model.SysNotifyReceiver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import cn.xshi.common.base.BaseService;
import cn.xshi.common.util.ExceptionUtil;
import javax.annotation.Resource;
/**
 * @Desc 通知接收人
 * @Author 邓纯杰
 * @CreateTime 2012-12-12 12:12:12
 */
@Service
@Slf4j
public class SysNotifyReceiverServiceImpl extends BaseService implements SysNotifyReceiverService {

	@Resource
	private SysNotifyReceiverDao sysNotifyReceiverDao;

	/**
	 * 初始化分页
	 * @param condition
	 * @return
	 */
	public List<SysNotifyReceiver> getSysNotifyReceiverListByCondition(Map<String, Object> condition){
		try {
			return sysNotifyReceiverDao.getSysNotifyReceiverListByCondition(condition);
		} catch (Exception e) {
			throw new ExceptionUtil(e.getMessage(),e.getCause());
		}
	}

	/**
	 *
	 * @param id
	 * @return
	 */
	public SysNotifyReceiver getSysNotifyReceiverById(String id){
		try {
			SysNotifyReceiver sysNotifyReceiver = sysNotifyReceiverDao.getSysNotifyReceiverById(id);
			Thread thread = new Thread(new NotifyReceiverWork(sysNotifyReceiver));
			thread.setDaemon(true);
			thread.start();
			return sysNotifyReceiver;
		} catch (Exception e) {
			throw new ExceptionUtil(e.getMessage(),e.getCause());
		}
	}

	/**
	 *
	 * @param condition
	 * @return
	 */
	public int delSysNotifyReceiver(Map<String, Object> condition){
		try {
			return sysNotifyReceiverDao.delSysNotifyReceiver(condition);
		} catch (Exception e) {
			throw new ExceptionUtil(e.getMessage(),e.getCause());
		}
	}
	
	/**
	 * 根据通知编号查找集合
	 * @param notify_id
	 * @return
	 */
	public List<SysNotifyReceiver> getSysNotifyReceiverListById(String notify_id){
		return sysNotifyReceiverDao.getSysNotifyReceiverListById(notify_id);
	}
	
	/**
	 * 更新已读
	 * @param condition
	 * @return
	 */
	public int updateSysNotifyReceiver(Map<String, Object> condition){
		try {
			return sysNotifyReceiverDao.updateSysNotifyReceiver(condition);
		} catch (Exception e) {
			throw new ExceptionUtil(e.getMessage(),e.getCause());
		}
	}

	/**
	 *
	 */
	class NotifyReceiverWork implements Runnable{

		SysNotifyReceiver sysNotifyReceiver;

		public NotifyReceiverWork(){

		}
		public NotifyReceiverWork(SysNotifyReceiver sysNotifyReceiver){
			this.sysNotifyReceiver = sysNotifyReceiver;
		}
		@Override
		public void run() {
			if(null != sysNotifyReceiver && sysNotifyReceiver.getStatus() == 0){
				try {
					Map<String, Object> condition = new HashMap<>();
					Date date = getDate();
					condition.put("readTime", date);
					condition.put("id", sysNotifyReceiver.getId());
					updateSysNotifyReceiver(condition);
				}catch (Exception e){
					log.error("更新已读出错：{}",e);
				}
			}
		}
	}
}
